/*
* S3M图层模型
* */

import LayerModel from "../LayerModel";
import store from "@/store/store";

// let i = 0;for(let layer of scene.layers.layerQueue){console.log(i, layer.name); i++}
// let i = 0;for(let layer of scene.layers.layerQueue){console.log(i, layer.name); console.log("lodRangeScale", layer.lodRangeScale);i++;}

export default class S3MLayerModel extends LayerModel {

  constructor(layerInfo){
    super(layerInfo);
    // this.layerInfo = layerInfo;
  }

  async addLayer(isFly){

    // let url = this.layerInfo.url;
    let layerInfo = this.layerInfo;
    if (!layerInfo.url) {
      console.error(`S3MLayerModel添加图层错误，图层名称:${layerInfo.name}。原因：url不能为空。`);
      return;
    }

    // 判断服务是否已经加载
    if (store.state.viewerLayers[layerInfo.url]) {
      console.error(`S3MLayerModel添加图层错误，图层名称:${layerInfo.name}，\nurl = ${layerInfo.url}。\n原因：该场景已经存在。`);
      return;
    }

    isFly = isFly == true ? true : false;
    if (layerInfo.loadModel === "open") {

      this.addLayerUseOpen(isFly, layerInfo);
      // this.addLayerBySubdomainUseOpen(isFly);

    } else {

      // console.log(`this.layerInfo`, this.layerInfo);
      // console.log(`this.layerInfo.subdomain`, this.layerInfo.subdomain);
      // 使用nginx代理
      if (layerInfo.subdomain) {
        this.addLayerBySubdomainConfig();
      } else if (layerInfo.url.endsWith("/config") > 0) { // 通过config加载

        // console.log("addLayerByConfig：" + this.layerInfo.url);
        this.addLayerByConfig();
      } else {
        // console.log("addLayerByRealspace" + this.layerInfo.url);
        this.addLayerByRealspace(); // 通过场景来加载
      }
    }

  }

  /**
   * 通过scene.open()的方式加载
   * @param isFly
   * @returns {Promise<void>}
   */
  async addLayerUseOpen(isFly, layerInfo){

    isFly = isFly || false;
    // 添加到场景
    let promis;
    try {

      // 使用多子域的方式
      if (layerInfo.subdomain) {
        promis = scene.open(layerInfo.subdomain.subdomainConfig.urlScheme, layerInfo.subdomain.name, {
          subdomains: this.layerInfo.subdomain.subdomainConfig.subdomains,
          autoSetView: isFly
        });
      } else { // 非多子域方式加载
        promis = scene.open(layerInfo.url, layerInfo.sceneName, {
          autoSetView: isFly
        });
      }

      promis.then(layers => {

        // console.log("layers", layers);
        // 设置图层属性
        this.setLayersParameters(layers);

        // 保存当前图层对象到模型
        this.childLayers = layers;
        // layerModel.isLoadLayer = true;

        // 将对象添加到图层列表中
        store.state.viewerLayers[this.layerInfo.url] = this;

      }).otherwise((err) => {
        console.error(`S3MLayerModel打开场景错误，图层名称:${layerInfo.name}，\nurl = ${layerInfo.url}。\n原因：${errInfo}。`);
        console.error(`err`, err);
      });

    } catch (errInfo) {
      console.error("打开场景错误", errInfo);
      console.error(`name = ${layerInfo.name}, url = ${layerInfo.subdomain ? layerInfo.subdomain.subdomainConfig.urlScheme : layerInfo.url}`);
    }
  }

  // 通过scene.open()的方式使用子域
  async addLayerBySubdomainUseOpen(isFly){

    // 添加到场景
    let promis;
    try {
      promis = scene.open(this.layerInfo.subdomain.subdomainConfig.urlScheme, this.layerInfo.subdomain.name, {
        subdomains: this.layerInfo.subdomain.subdomainConfig.subdomains,
        autoSetView: isFly
      });
    } catch (errInfo) {
      console.error("打开场景错误", errInfo);
      console.error(`name = ${this.layerInfo.subdomain.name}, url = ${this.layerInfo.subdomain.subdomainConfig.urlScheme}`);
    }

    promis.then(layers => {

      // console.log("layers", layers);
      // 设置图层属性
      this.setLayersParameters(layers);

      // 保存当前图层对象到模型
      this.childLayers = layers;
      // layerModel.isLoadLayer = true;

      // 将对象添加到图层列表中
      store.state.viewerLayers[this.layerInfo.url] = this;

    }).otherwise((err) => {
      console.error(`S3MLayerModel添加图层错误，图层名称:${this.layerInfo.name}，\nurl = ${this.layerInfo.url}。\n原因：${errInfo}。`);
      console.error(`err`, err);
    });
  }

  // 使用子域
  async addLayerBySubdomainConfig(){
    let url = this.layerInfo.url;

    let promis = scene.addS3MTilesLayerByScp(url, this.layerInfo.subdomain);
    promis.then(layer => {

      // console.log(`layer`, layer);
      // 设置图层属性
      this.setLayersParameters(layers);

      // 保存当前图层对象到模型
      this.childLayers = [layer];

      // console.log(`store.state`, store.state);
      // console.log(`url`, url);

      // 将对象添加到图层列表中
      store.state.viewerLayers[url] = this;

    });
  }

  // iServerLayer
  async addLayerByConfig(){

    let url = this.layerInfo.url;

    let promis = scene.addS3MTilesLayerByScp(url, { name: this.layerInfo.name });
    promis.then(layer => {

      // console.log(`layer`, layer);
      // 设置图层属性
      this.setLayersParameters(layers);

      // 保存当前图层对象到模型
      this.childLayers = [layer];

      // console.log(`store.state`, store.state);
      // console.log(`url`, url);

      // 将对象添加到图层列表中
      store.state.viewerLayers[url] = this;

    });
  }

  // 添加图层：整个iServer场景
  async addLayerByRealspace(isFlyTo){

    let url = this.layerInfo.url;

    // 判断服务是否已经加载
    if (store.state.viewerLayers[url]) {
      console.error(`S3MLayerModel添加图层错误，图层名称:${this.layerInfo.name}，url = ${url}\n。原因：该场景已经存在。`);
      return;
    }

    // 获取场景中的所有子图层
    let datas = await axios.get(`${url}/datas.json`);
    if (!datas) {
      console.error(`S3MLayerModel添加图层错误，图层名称:${this.layerInfo.name}，url = ${url}\n。原因：服务无法访问。`);
      return;
    }

    let promises = [];
    for (let data of datas) {
      // console.log(`url = ${data.path}/config, name = ${data.name}`);

      // 添加到场景
      let promis = scene.addS3MTilesLayerByScp(`${data.path}/config`, { name: data.name });
      promises.push(promis);
    }

    Promise.all(promises).then(layers => {

      // console.log("layers", layers);
      // 设置图层属性
      this.setLayersParameters(layers);

      // 保存当前图层对象到模型
      this.childLayers = layers;
      // layerModel.isLoadLayer = true;

      // 将对象添加到图层列表中
      store.state.viewerLayers[url] = this;

      if (isFlyTo) {
        this.flyTo();
      }

    }).catch(errInfo => {
      console.error(`S3MLayerModel添加图层错误，图层名称:${this.layerInfo.name}，\nurl = ${url}。\n原因：${errInfo}。`);
    });
  }

  /**
   * 设置图层的属性
   * @param layers
   */
  setLayersParameters(layers){

    let layerInfo = this.layerInfo;

    let show = layerInfo.show == true ? true : false; // 图层是否显示
    let selectEnabled = layerInfo.selectEnabled || false; // 图层是否可查
    let maxTransparentAlpha = layerInfo.alpha; // 图层的透明度
    let brightness = layerInfo.brightness; // 图层亮度值
    let saturation = layerInfo.saturation; // 图层饱和度

    let visibleDistanceMax = layerInfo.visibleDistanceMax; // 最大可见距离
    let bottomAltitude = layerInfo.bottomAltitude; // 底部高层
    let fillForeColor = layerInfo.fillForeColor; // 设置填充前景色
    let lineWidth = layerInfo.lineWidth; // 设置线框宽度
    let lineColor = layerInfo.lineColor; // 设置线框颜色
    let configHypsometricSetting = layerInfo.hypsometricSetting; // 设置填充前景色

    if (!(layers instanceof Array)) {
      layers = [layers];
    }

    for (var layer of layers) {
      layer.style3D.lineWidth = 0.5;
      layer.style3D.lineColor = new Cesium.Color(60 / 255, 60 / 255, 60 / 255, 1);
      layer.style3D.fillStyle = Cesium.FillStyle.Fill_And_WireFrame;
      layer.wireFrameMode = Cesium.WireFrameType.EffectOutline;
    }

    for (let layer of layers) {



      // // 设置查询参数
      // layer.setQueryParameter({
      //   url: 'http://www.supermapol.com/realspace/services/data-jinjiang/rest/data',
      //   dataSourceName: 'jinjiang',
      //   dataSetName: 'test',
      //   keyWord: 'SmID'
      // });

      // layer.setQueryParameter({
      //   url:"http://localhost:8090/iserver/services/data-dixiaEr/rest/data",
      //   dataSourceName : "BIMQuyer",
      //   dataSetName:"tianhuaban",
      //   // isMerge : true // 该图层是否为合并数据集的，如果是则不用指定数据集名称。
      // });
      //
      // console.log(`layer.datasetInfo()`, layer.datasetInfo());
      // layer.datasetInfo().then((info)=>{
      //   console.log(`info`, info);
      // });

      // 调度策略
      layer.LoadingMode = Cesium.LoadingPriorityMode.Child_Priority_NonLinear;

      // 图层的可见性
      layer.visible = show;

      // 设置图层是否可以被选择
      layer.selectEnabled = selectEnabled || false;
      // console.log(`store.state.queryConfigs`, this.layerInfo.queryParameters);
      // 添加查询参数
      let queryParameters = layerInfo.queryParameters;
      console.log(`queryParameters`, queryParameters);
      if (queryParameters) {

        let queryConfigs = store.state.queryConfigs;
        if (queryParameters instanceof Array) {
          // store.state.queryConfigs = store.state.queryConfigs.concat(queryParameters);
          for (const queryParamete of queryParameters) {
            queryConfigs[`${layerInfo.realName}${new Date().getTime()}`] = queryParamete;
          }
        } else {
          queryConfigs[layerInfo.realName] = queryParameters;
        }

        if (queryParameters.queryModel === "BIM") {
          let querLayer = viewer.scene.layers.find(layerInfo.realName);
          querLayer.setQueryParameter({
            url: "http://www.supermapol.com/realspace/services/data-BIMbuilding/rest/data",
            dataSourceName: "BIMBuilding",
            keyWord: "SmID"
            // isMerge: true
          });

          // viewer.pickEvent.addEventListener((feature) => {
          //   console.log(`feature`, feature);
          // });
        }

      }

      // 图层的透明度
      if (maxTransparentAlpha || maxTransparentAlpha === 0) {
        layer.maxTransparentAlpha = maxTransparentAlpha;
      }

      // 图层亮度值
      if (brightness || brightness === 0) {
        layer.brightness = brightness;
      }

      // 图层饱和度
      if (saturation || saturation === 0) {
        layer.saturation = saturation;
      }

      // 设置图层的最大可见距离值
      if (visibleDistanceMax) {
        layer.visibleDistanceMax = visibleDistanceMax;
      }

      // 是否需要刷新图层
      let isNeedRefresh = false;

      // 设置底部高程
      let style3D = layer.style3D;
      if (bottomAltitude) {
        style3D.bottomAltitude = bottomAltitude;

        isNeedRefresh = true;
      }

      // 设置填充前景色
      if (fillForeColor && fillForeColor.length > 2) {
        style3D.fillForeColor = new Cesium.Color(fillForeColor[0], fillForeColor[1], fillForeColor[2], fillForeColor[3] || 1);

        isNeedRefresh = true;
      }

      if (lineWidth || lineWidth === 0) {
        style3D.fillStyle = Cesium.FillStyle.Fill_And_WireFrame; // 填充和线框模式
        style3D.lineWidth = lineWidth;
        isNeedRefresh = true;
      }

      if (lineColor && lineColor.length > 2) {
        style3D.lineColor = new Cesium.Color(lineColor[0], lineColor[1], lineColor[2], lineColor[3] || 1);
        isNeedRefresh = true;
      }

      // 设置后需刷新图层
      if (isNeedRefresh) {
        layer.style3D = style3D;
        layer.refresh();
      }

      // 分层设色
      if (configHypsometricSetting) {

        let hypsometricSetting = new Cesium.HypsometricSetting();
        if (configHypsometricSetting.minVisibleValue) {
          hypsometricSetting.MinVisibleValue = configHypsometricSetting.minVisibleValue;
        }

        if (configHypsometricSetting.maxVisibleValue) {
          hypsometricSetting.MaxVisibleValue = configHypsometricSetting.maxVisibleValue;
        }

        // 设置颜色表
        let colorTable = new Cesium.ColorTable();
        let colorTables = configHypsometricSetting.colorTables; // 颜色表
        for (const color of colorTables) {
          colorTable.insert(
            color.height || color.height === 0 ? color.height : 99999,
            new Cesium.Color((color.red || 0) / 255, (color.green || 0) / 255, (color.blue || 0) / 255, color.alpha || 1)
          );
        }

        layer.hypsometricSetting = {
          hypsometricSetting: hypsometricSetting,
          analysisMode: Cesium.HypsometricSettingEnum.AnalysisRegionMode.ARM_ALL
        };

        //设置图层分层设色属性

        // var colorTable = new Cesium.ColorTable();
        colorTable.insert(150, new Cesium.Color(1, 0, 0));
        colorTable.insert(30, new Cesium.Color(0, 0, 1));
        hypsometricSetting.ColorTable = colorTable;

      }

    }
  }

  // 飞行到指定图层
  flyTo(){

    // 经纬度坐标定位
    let isFly = super.flyTo(); // 调用父类的飞行方法：经纬度坐标定位、笛卡三维笛卡尔坐标定位

    // 没有在配置文件中定义坐标位置坐标
    if (!isFly) {

      let sceneLayers = this.childLayers;
      if (sceneLayers && sceneLayers.length < 1) {
        alert("图层未加载完成或图层为空，请稍后再试！");
        return;
      }

      let ceterCartesianPosition = sceneLayers[0]._position;
      // let boundingSphere = new Cesium.BoundingSphere(Cesium.Cartesian3.fromDegrees(ceterCartesianPosition.x, ceterCartesianPosition.y, ceterCartesianPosition.z), 200);
      let boundingSphere = new Cesium.BoundingSphere(ceterCartesianPosition, sceneLayers.length > 1 ? 2000 : 1000);
      let camera = scene.camera;
      camera.flyToBoundingSphere(boundingSphere);
    }

  }

  // 设置图层的可见性
  setVisible(isVisible){
    // console.log(`setVisible`, isVisible);

    let sceneLayers = this.childLayers;
    for (let layer of sceneLayers) {
      layer.visible = isVisible;
      layer.refresh();
    }
  }

  // 删除图层
  removeLayer(){

    let removeLayers = this.childLayers;
    for (let layer of removeLayers) {
      scene.layers.remove(layer.name);
    }

    if (store.state.viewerLayers[url]) {
      store.state.viewerLayers[url] = undefined;
      delete store.state.viewerLayers[url];
    }

    return true;
  }

  /**
   * 删除所有图层
   */
  static removeAll(destroy = true, viewer = window.viewer){
    viewer.scene.layers.removeAll(destroy);
  }

  // 判断字符串是否以某个字符串结尾
  stringEndWith(str, endStr){
    if (!str) {
      return false;
    }
    let d = this.length - endStr.length;
    return (d >= 0 && this.lastIndexOf(endStr) == d);
  }
}

